<?php
	
	if (!class_exists('ctl_cart'))
	{
		require_once(CORE_DIR.'/shop/controller/ctl.cart.php');
	}
	class collocate_goods_cart_ctl extends ctl_cart
	{
		function collocate_goods_cart_ctl(&$system)
		{
			parent::ctl_cart($system);
			$this->objCollocAddon = &$this->system->loadModel('plugins/collocate_goods/collocAddon');
			$this->objCollocAddon->_checkMember($this->member);
			//会员登录合并搭配商品信息	没在会员登陆后合并
			if ($this->objCollocAddon->memberLogin)
			{
				$this->objCollocAddon->mergeCollocAddon();
			}
		}

		function addGoodsToCart($gid=0, $pid=0, $stradj='', $pmtid=0, $num=1)
		{
			require('post_colloc.php');
			if ($_POST['goods']['colloc'] && $_POST['goods']['adjunct'])
			{
				unset($_POST['goods']['adjunct']);
			}
			
			if ($_POST['goods']['colloc'])
			{
				if ($aRule = $this->objCollocAddon->createColloc($_POST['goods']))
				{
					$this->objCollocAddon->saveCollocCart($aRule);
				}
			}
			$aParams = $this->objCart->getParams($_POST['goods'],$gid, $pid, $stradj, $pmtid);
			if($aParams['pid'] == -1){
				$this->begin($_SERVER['HTTP_REFERER']);
				trigger_error(__('加入购物车失败：无此货品'),E_USER_ERROR);
				$this->end();
			}
			$_num = intval($aParams['num']);
			if($_num){
				$num = $_num;
			}else{
				$num = intval($num);
			}
			if(!$num) $num = 1;

			$status = $this->objCart->addToCart('g', $aParams, $num);
			if($status === 'notify'){
				$this->begin($this->system->mkUrl("product","gnotify",array($gid, $pid)));
				$this->setError(10001);
				if($_POST['mini_cart']){
					header("HTTP/1.0 404 Not Found");
				}
				trigger_error(__('加入购物车失败：商品缺货，转入缺货登记'),E_USER_ERROR);
				$this->end();
			}elseif(!$status){
				$this->begin($_SERVER['HTTP_REFERER']);
				$this->setError(10002);
				if($_POST['mini_cart']){
					header("HTTP/1.0 404 Not Found");
				}
				trigger_error(__('加入购物车失败: 商品库存不足或者提交参数错误！'),E_USER_ERROR);
				$this->end();
			}else{
				if($_POST['fastbuy']){
					$this->checkout();
				}else{
					if($_POST['mini_cart']){
						$this->view(1);
						exit;
					}
					$this->redirect('cart');
				}
			}
		}

		function index()
		{
			$this->title = __('查看购物车');
			$sale = &$this->system->loadModel('trading/sale');
			$trading = $sale->getCartObject($this->cart,$GLOBALS['runtime']['member_lv'],true);
			
			if ($this->objCollocAddon->splitAddon())
			{
				$tmpProducts = $trading['products'];	//将原先的商品记录下来
				$collocTrading = $this->mergeCollocTrading(&$collocGoods);
				$mergeTrading[] = $trading;
				$mergeTrading[] = $collocTrading;
				$trading = $this->objCollocAddon->mergeCollocTrading($mergeTrading,$GLOBALS['runtime']['member_lv'],true);	
				$this->pagedata['showColloc'] = true;
				$this->pagedata['collocGoods'] = &$collocGoods;
				$trading['products'] = $tmpProducts;	//复原原有商品
			}
			else $this->pagedata['showColloc'] = false;
			$number=count($trading['products'])+count($trading['gift_e'])+count($trading['package']);
			if($number!=$_COOKIE['CART_COUNT']){
				$this->system->setCookie('CART_COUNT',$number);
			}
			$this->pagedata['trading'] = &$trading;
			$cur = &$this->system->loadModel('system/cur');
			$aCur = $cur->getFormat($this->system->request['cur']);
			$this->pagedata['currency'] = json_encode($aCur);

			header("Expires: -1");
			header("Pragma: no-cache");
			header("Cache-Control: no-cache, no-store");
			$this->__tmpl = dirname(__FILE__)."/view/cart/index.html";
			$this->output();
		}

		function view($mini=0)
		{
			$sale = &$this->system->loadModel('trading/sale');
			$this->cart = $this->objCart->getCart('all');
			$trading = $sale->getCartObject($this->cart,$GLOBALS['runtime']['member_lv'],true);
			//存在搭配规则
			if ($this->objCollocAddon->splitAddon())
			{
				$collocTrading = $this->mergeCollocTrading(&$collocGoods);
				$mergeTrading[] = $trading;
				$mergeTrading[] = $collocTrading;
				$trading = $this->objCollocAddon->mergeCollocTrading($mergeTrading,$GLOBALS['runtime']['member_lv'],true);
			}
			foreach ($trading['products'] as $v)
			{
				$numCount[] = $v['nums'];
			}
			$numCount = array_sum($numCount);
			if($numCount!=$_COOKIE['CART_NUMBER']){
				$this->system->setCookie('CART_NUMBER',$numCount);
			}
			$number=count($trading['products'])+count($trading['gift_e'])+count($trading['package']);
			if($number!=$_COOKIE['CART_COUNT']){
				$this->system->setCookie('CART_COUNT',$number);
			}
			$this->pagedata['trading'] = &$trading;
			$this->pagedata['cartCount'] = $_COOKIE['CART_COUNT'];
			$this->pagedata['cartNumber'] = $_COOKIE['CART_NUMBER'];
			$this->__tmpl = $mini?dirname(__FILE__).'/view/cart/mini_cart.html':dirname(__FILE__).'/view/cart/view.html';
			$this->output();
		}
		
		/**
		 *	cartNum[co][colloc-79-314-5-time()][1274670317][239]=>3 colloc,79,314,5,time()@1274670317@239
		 *	cartNum[main][colloc-79-314-5-time()]=>3
		 *	
		 */
		function removeCart($objType='g',$key='')
		{	
			if ('main' == $objType)
			{
				$key = str_replace(',','-',$key);
				$num = $_POST['cartNum'][$objType][$key];
				$this->objCollocAddon->removeCollocAddon($objType,$key);
			}
			elseif ('co' == $objType)
			{
				list($coKey,$coid,$pid) = explode('@',$key);
				$coKey = str_replace(',','-',$coKey);
				$num = $_POST['cartNum'][$objType][$coKey][$coid][$pid];
				$this->objCollocAddon->removeCollocAddon($objType,$coKey,$coid,$pid);
			}
			else
			{
				$this->objCart->removeCart($objType, $_POST['cartNum'][$objType]);
				if ('all' == $objType)
				{
					$this->objCollocAddon->removeCollocAddon($objType,$key);
				}
			}
			$this->cartTotal();
		}

		function updateCart($objType='g', $key='')
		{
			//error_log(print_r($_POST,true),3,__FILE__.'.'.__FUNCTION__.'._POST.log');//alone add
			if ('main' == $objType)
			{	//$key => co,gid,pid,pmt_id,time()
				$key = str_replace(',','-',$key);
				$num = $_POST['cartNum'][$objType][$key];
				if (!$this->objCollocAddon->updateCollocAddon($objType,$key,$num,$aMsg)){
					//error_log(print_r($aMsg,true),3,__FILE__.'.'.__FUNCTION__.'.aMsg.log');//alone add
					echo $aMsg;
				}else{
					$this->cartTotal();
				}
			}
			elseif ('co' == $objType)
			{
				//$key => co,gid,pid,pmt_id,time()@coid@copid
				list($coKey,$coid,$pid) = explode('@',$key);
				$coKey = str_replace(',','-',$coKey);
				$num = $_POST['cartNum'][$objType][$coKey][$coid][$pid];
				if ($this->objCollocAddon->updateCollocAddon($objType,$coKey,$num,$aMsg,$coid,$pid)){
					echo $aMsg;
				}else{
					$this->cartTotal();
				}
			}
			else
			{
				$key = str_replace('@', '-', $key);
				$nQuantity = $_POST['cartNum'][$objType][$key];
				switch($objType) {
					case 'f':
						$oCart->member['member_lv_id'] =$GLOBALS['runtime']['member_lv'];
						$oCart->member['point'] = $this->member['point'];
						break;
					case 'g':
						break;
					case 'p':
						break;
					default:
						break;
				}
				if(!$this->objCart->updateCart($objType, $key, $nQuantity,$aError)){
					echo implode('',$aError);
				}else{
					$this->cartTotal();
				}
			}
		}

		function cartTotal()
		{
			/* 调用构造函数 更新cart */
			$this->collocate_goods_cart_ctl();
			$sale = &$this->system->loadModel('trading/sale');
			$trading = $sale->getCartObject($this->cart,$GLOBALS['runtime']['member_lv'],true);
			if ($this->objCollocAddon->splitAddon())
			{
				$tmpProducts = $trading['products'];	//将原先的商品记录下来
				$collocTrading = $this->mergeCollocTrading(&$collocGoods);
				$mergeTrading[] = $trading;
				$mergeTrading[] = $collocTrading;
				$trading = $this->objCollocAddon->mergeCollocTrading($mergeTrading,$GLOBALS['runtime']['member_lv'],true);
				
				$number=count($trading['products'])+count($trading['gift_e'])+count($trading['package']);
				if($number!=$_COOKIE['CART_COUNT']){
					$this->system->setCookie('CART_COUNT',$number);
				}
				//$this->pagedata['collocGoods'] = $collocGoods;
				$trading['products'] = $tmpProducts;	//复原原有商品
			}
			$this->pagedata['trading'] = &$trading;
			$this->__tmpl = dirname(__FILE__).'/view/cart/cart_total.html';
			$this->output();
		}

		function checkout($isfastbuy=0)
		{
			if($isfastbuy){
				$this->cart = $this->objCart->getCart('all',$_COOKIE['Cart_Fastbuy']);
				$this->products = $this->cart['g'];
				$_POST['isfastbuy'] = 1;
			}
			/* alone add start */
			$countNum = 0;
			if ($this->objCollocAddon->splitAddon())
			{
				//计算搭配商品中的商品数量
				$collocTrading = $this->objCollocAddon->getShopexCartFormat(&$collocGoods);		//搭配商品
				foreach ($collocGoods as $g)
				{
					$countNum += count($g['goods']);
					$countNum += count($g['products']);				
				}
				$this->pagedata['showColloc'] = true;
			}
			else $this->pagedata['showColloc'] = false;
			/* alone add end */
			$this->title = __('填写购物信息');
			if(count($this->products['cart'])+count($this->pkggoods)+count($this->gifts)+$countNum == 0){
				$this->redirect('cart');
				exit;
			}

			if(!$this->member['member_id'] && !$_COOKIE['ST_ShopEx-Anonymity-Buy']){
				$this->redirect('cart','loginBuy',array($_POST['isfastbuy']));
				exit;
			}
			//调用plugins/mdl:collocAddon:getCheckout
			$aOut = $this->objCollocAddon->getCheckout($this->cart, $this->member, $this->system->request['cur']);
			$this->pagedata['has_physical'] = $aOut['has_physical'];
			$this->pagedata['minfo'] = $aOut['minfo'];
			$this->pagedata['areas'] = $aOut['areas'];
			$this->pagedata['dlytime'] = date('Y-m-d', time()+floatval($this->system->getConf('site.delivery_time'))*3600*24);
			$this->pagedata['currencys'] = $aOut['currencys'];
			$this->pagedata['currency'] = $aOut['currency'];
			$payment = $this->system->loadModel('trading/payment');
			$payment->showPayExtendCon($aOut['payments']);
			$this->pagedata['payments'] = $aOut['payments'];
			if ($aOut['payments']){
				foreach($aOut['payments'] as $key => $val){
					if(!$this->member['member_id'] && $val['pay_type'] == 'deposit'){
						unset($this->pagedata['payments'][$key]);
						continue;
					}
					$this->pagedata['payments'][$key]['config']=unserialize($val['config']);
				}
			}
			$this->pagedata['config'] = unserialize($aOut['payments']['config']);
			$this->pagedata['trading'] = $aOut['trading'];

			if($this->member['member_id']){
				$member = &$this->system->loadModel('member/member');
				$addrlist = $member->getMemberAddr($this->member['member_id']);
				foreach($addrlist as $rows){
					if(empty($rows['tel'])){
						$str_tel = __('手机：').$rows['mobile'];
					}else{
						$str_tel = __('电话：').$rows['tel'];
					}
					$addr[] = array('addr_id'=> $rows['addr_id'],'def_addr'=>$rows['def_addr'],'addr_region'=> $rows['area'],
									'addr_label'=> $rows['addr'].__(' (收货人：').$rows['name'].' '.$str_tel.__(' 邮编：').$rows['zip'].')');
				}
				$this->pagedata['trading']['receiver']['addrlist'] = $addr;
				$this->pagedata['is_allow'] = (count($addr)<5 ? 1 : 0);
			}else{
				setcookie('S[ST_ShopEx-Anonymity-Buy]','',time()-1000);
			}
			$this->__tmpl = dirname(__FILE__).'/view/cart/checkout.html';
			$this->output();
		}

		function total()
		{
			$tarea = explode(':', $_POST['area'] );
			$_POST['area'] = $tarea[count($tarea)-1];
			$this->pagedata['trading'] = $this->objCollocAddon->checkoutInfo($this->cart, $this->member, $_POST);
			$this->__tmpl=dirname(__FILE__).'/view/cart/checkout_total.html';
			$this->output();
		}

		function shipping()
		{
			$sale = &$this->system->loadModel('trading/sale');
			$trading = $sale->getCartObject($this->cart,$GLOBALS['runtime']['member_lv'],true);
			/* alone add start */
			if ($this->objCollocAddon->splitAddon())
			{
				$tmpProducts = $trading['products'];	//将原先的商品记录下来
				$collocTrading = $this->mergeCollocTrading(&$collocGoods);
				$mergeTrading[] = $trading;
				$mergeTrading[] = $collocTrading;
				$trading = $this->objCollocAddon->mergeCollocTrading($mergeTrading,$GLOBALS['runtime']['member_lv'],true);
				$trading['products'] = $tmpProducts;	//复原原有商品
			}
			/* alone add end */
			$shipping = &$this->system->loadModel('trading/delivery');
			$aShippings = $shipping->getDlTypeByArea($_POST['area']);
			foreach($aShippings as $k=>$s){
				$aShippings[$k]['price'] = cal_fee($s['expressions'],$trading['weight'],$trading['pmt_b']['totalPrice'],$s['price']);
				$s['pad']==0?$aShippings[$k]['has_cod'] = 0:$aShippings[$k]['has_cod'] = 1;
				if($s['protect']==1){
					$aShippings[$k]['protect'] = true;
				}else{
					$aShippings[$k]['protect'] = false;
				}
			}
			$this->pagedata['shippings'] = $aShippings;
			$this->display(dirname(__FILE__).'/view/cart/checkout_shipping.html');
		}

		function applycoupon()
		{
		  $this->begin($this->system->mkUrl('cart','index'),null,E_ERROR | E_USER_ERROR | E_USER_WARNING);
			$oCoupon = &$this->system->loadModel('trading/coupon');
			if (!empty($_POST['coupon'])) {
				$oSale = &$this->system->loadModel('trading/sale');
				$oPromotion = &$this->system->loadModel('trading/promotion');
				$trading = $oSale->getCartObject($this->cart, $GLOBALS['runtime']['member_lv'], true);
				/* alone add start */
				if ($this->objCollocAddon->splitAddon())
				{
					$tmpProducts = $trading['products'];	//将原先的商品记录下来
					$collocTrading = $this->mergeCollocTrading(&$collocGoods);
					$mergeTrading[] = $trading;
					$mergeTrading[] = $collocTrading;
					$trading = $this->objCollocAddon->mergeCollocTrading($mergeTrading,$GLOBALS['runtime']['member_lv'],true);
					$trading['products'] = $tmpProducts;	//复原原有商品
				}
				/* alone add end */
				if ($trading['ifCoupon']) {
					if(!$oPromotion->apply_coupon_pmt($trading, $_POST['coupon'], $GLOBALS['runtime']['member_lv'])){
						$this->end(false, __('无效优惠券'),$this->system->mkUrl('cart','index') );
					}
				}else{
	//                $this->setError('10000');
					trigger_error(__('有促销活动期间是不否允许使用优惠券'),E_USER_ERROR);
					$this->end(false, __('有促销活动期间是不否允许使用优惠'), $this->system->mkUrl('cart', 'index'));
				}
			}else{
				trigger_error(__('请输入优惠券'),E_USER_ERROR);
				$this->end(false, __('请输入优惠券'), $this->system->mkUrl('cart', 'index'));
			}

			  $this->end(true, __('成功加入购物车'), $this->system->mkUrl('cart', 'index'));
		}

		function mergeCollocTrading(&$collocGoods,$mergeProducts=false)
		{
			$tmpTrading = $this->objCollocAddon->getShopexCartFormat($collocGoods);
			$collocTrading = $this->objCollocAddon->mergeCollocTrading($tmpTrading,$GLOBALS['runtime']['member_lv'],true,$mergeProducts);
			return $collocTrading;
		}
	}
?>